package com.chaodev.base.utils.security;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import java.nio.charset.StandardCharsets;

/**
 * 基于hutool进行二次封装的国密算法
 */
public class SmHelper {
    /**
     * SM2非对称加密
     * @param data 明文
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encodeSm2(String data,String publicKey){
        SM2 sm2 = SmUtil.sm2(null,publicKey);
        return  sm2.encryptBcd(data, KeyType.PublicKey);
    }

    /**
     * SM2非对称解密
     * @param encryptStr 密文
     * @param privateKey 私钥
     * @return 明文
     */
    public static String decodeSm2(String encryptStr,String privateKey){
        SM2 sm2 = SmUtil.sm2(privateKey,null);
        return StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));
    }
    /**
     * 获取sm2公钥和私钥
     * @return
     */
    public static SecureKeyPair getSm2Key(){
        SecureKeyPair secureKeyPair=new SecureKeyPair();
        SM2 sm2 = SmUtil.sm2();
        secureKeyPair.setPrivateKey(sm2.getPrivateKeyBase64());
        secureKeyPair.setPublicKey(sm2.getPublicKeyBase64());
        return secureKeyPair;
    }

    /**
     * SM3摘要算法
     * @param data
     * @return
     */
    public static String encodeSm3(String data){
        return SmUtil.sm3(data);
    }
    public static String encodeSm4(String data,String key){
        byte[] keyBytes=key.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto sm4 = SmUtil.sm4(keyBytes);
        String encryptHex = sm4.encryptHex(data);
        return encryptHex;
    }
    public static String decodeSm4(String data,String key){
        byte[] keyBytes=key.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto sm4 = SmUtil.sm4(keyBytes);
        String decryptStr = sm4.decryptStr(data, CharsetUtil.CHARSET_UTF_8);
        return decryptStr;
    }
}
